# coding: utf-8

from datetime import date

from exts import rdb


class IDCreator(object):
    """
    创建ID
    """

    @staticmethod
    def create_id(key: str, year_related: bool = False, length: int = 10, prefix: str = ""):
        """
        用redis创建id
        :param key:
        :param year_related: True 满一年重置流水号
        :param length: 除去前缀后长度
        :param prefix: 前缀
        :return:
        """
        curr_year = date.today().year
        if year_related:
            rdb_year = rdb.get("curr_year")
            if int(rdb_year) != curr_year:
                rdb.set("curr_year", curr_year)
                rdb.delete(key)
            length -= 4

        value = str(rdb.incr(key))
        value = value.rjust(length, "0")
        if year_related:
            value = str(curr_year) + value
        value = prefix + value
        return value
